package eu.vconect.orch;

import java.util.Random;

import org.apache.log4j.Logger;

public class SimpleOrchestrator implements Orchestrator, Runnable {
	private static Logger LOG = Logger.getLogger(SimpleOrchestrator.class);
	private static final int FROM = 4000;	// milliseconds
	private static final int TO = 7000;		// milliseconds
	private Random random = new Random();
	private boolean on = false;
	private HangoutSession hangout;
	private Object lock = new Object();
	private String participant = null;
	private Thread thread = null;
	
	public SimpleOrchestrator(HangoutSession hangout) {
		this.hangout = hangout;
	}
	
	public synchronized void start() {
		if ( on && thread != null ) {
			if ( thread.isAlive() )
				LOG.warn("SimpleOrchestrator thread is started and alive.");
			else
				LOG.warn("SimpleOrchestrator thread is started but it isn't alive.");
		} else {
			on = true;
			thread = new Thread(this);
			thread.start();
		}		
	}
	
	public synchronized void stop() {
		on = false;
		thread = null;		
	}
	
	public synchronized boolean isRunning() {
		return on && thread != null && thread.isAlive();
	}
	
	public String cutTo(String participantId) {
		try {
			LOG.debug("Participant [" + participantId + "] is waiting on the lock to be released.");
			synchronized (lock) {
				lock.wait();				
			}
			LOG.debug("Lock released by SimpleOrchestrator.");
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		return participant;
	}
	
	@Override
	public void run() {
		LOG.debug("SimpleOrchestrator thread started.");
		while (on) {
			try {
				long sleep = FROM + random.nextInt((TO - FROM));
				LOG.debug("Sleep " + sleep + "ms ...");
				Thread.sleep(sleep);
				String[] participants = hangout.getParticipantsMap().keySet().toArray(new String[0]);
				if ( participants.length > 0 ) {
					int index = random.nextInt(participants.length);
					participant = participants[index];
					LOG.debug("Participant index [" + index + "] is chosen [" + participant + "]. Blocked http requests are notified...");
					synchronized (lock) {
						lock.notifyAll();									
					}
				} else {
					LOG.warn("There are no participants to choose from! Blocked http requests are not notified.");					
				}				
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}		
		LOG.debug("SimpleOrchestrator thread finished.");
	}	
}
